package com.changgou.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.config.WxProperties;
import com.changgou.entity.HttpClient;
import com.changgou.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liyipeng
 * @date 2021-07-01 19:32
 */
@Service
public class WeixinPayServiceImpl implements WeixinPayService {

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.partner}")
    private String partner;

    @Value("${weixin.partnerkey}")
    private String partnerkey;

    @Value("${weixin.notifyurl}")
    private String notifyurl;

    @Autowired
    private WxProperties wxProperties;


    //模拟浏览器发送一个请求 获取响应（XML 装成map 返回）
    @Override
    public Map<String, String> createNative(Map<String, String> parameter) {
        try {
            //1.创建参数对象map 进行参数的组装
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("appid", wxProperties.getAppid());              //应用ID
            paramMap.put("mch_id", wxProperties.getPartner());          //商户ID号
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());;   //随机数
            paramMap.put("body", "青橙商城");	                        //订单描述
            paramMap.put("out_trade_no", parameter.get("out_trade_no"));    //商户订单号
            paramMap.put("total_fee", parameter.get("total_fee"));      //交易金额 单位是分
            paramMap.put("spbill_create_ip", "127.0.0.1");  //终端IP
            paramMap.put("notify_url", wxProperties.getNotifyurl());   //回调地址
            paramMap.put("trade_type", "NATIVE");               //交易类型
            //==========================attachMap={username:zhangsan ,type:1}======================******************************==========
            Map<String,String> attachMap = new HashMap<>();
            attachMap.put("username",parameter.get("username"));
            attachMap.put("type",parameter.get("type"));

            //JSON
            paramMap.put("attach", JSON.toJSONString(attachMap));

            //签名 todo   将map 转换成XML 的是会自动添加签名
            //2.将map转成XML
            String xmlParam = WXPayUtil.generateSignedXml(paramMap, wxProperties.getPartnerkey());
            //3.使用httpclient 工具类 进行模拟浏览器发送请求 统一下单API
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(xmlParam);
            httpClient.post();
            //4.使用Httpclient 工具类 进行模拟浏览器接收响应
            String content = httpClient.getContent();
            /*TODO 把下面的哪一行注释了*/
            System.out.println("XML内容："+content);
            //5.将xml 转成MAP (里面有code_url)
            Map<String, String> contentMap = WXPayUtil.xmlToMap(content);
            Map<String,String> resultMap = new HashMap<>();

            resultMap.put("total_fee", parameter.get("total_fee"));
            resultMap.put("out_trade_no",parameter.get("out_trade_no"));
            resultMap.put("code_url",contentMap.get("code_url"));

            //6.返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建二维码
     * @param out_trade_no : 客户端自定义订单编号
     * @param total_fee    : 交易金额,单位：分
     */
    /*@Override
    public Map createNative(String out_trade_no, String total_fee){
        try {
            //1、封装参数
            Map param = new HashMap();
            param.put("appid", appid);                              //应用ID
            param.put("mch_id", partner);                           //商户ID号
            param.put("nonce_str", WXPayUtil.generateNonceStr());   //随机数
            param.put("body", "青橙");                            	//订单描述
            param.put("out_trade_no",out_trade_no);                 //商户订单号
            param.put("total_fee", total_fee);                      //交易金额
            param.put("spbill_create_ip", "127.0.0.1");           //终端IP
            param.put("notify_url", notifyurl);                    //回调地址
            param.put("trade_type", "NATIVE");                     //交易类型

            //2、将参数转成xml字符，并携带签名
            String paramXml = WXPayUtil.generateSignedXml(param, partnerkey);

            ///3、执行请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(paramXml);
            httpClient.post();

            //4、获取参数
            String content = httpClient.getContent();
            Map<String, String> stringMap = WXPayUtil.xmlToMap(content);
            System.out.println("stringMap:"+stringMap);

            //5、获取部分页面所需参数
            Map<String,String> dataMap = new HashMap<String,String>();
            dataMap.put("code_url",stringMap.get("code_url"));
            dataMap.put("out_trade_no",out_trade_no);
            dataMap.put("total_fee",total_fee);

            return dataMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    /***
     * 查询订单状态
     * @param out_trade_no : 客户端自定义订单编号
     * @return
     */
    @Override
    public Map queryPayStatus(String out_trade_no) {
        try {
            //1.封装参数
            Map param = new HashMap();
            param.put("appid",appid);                            //应用ID
            param.put("mch_id",partner);                         //商户号
            param.put("out_trade_no",out_trade_no);              //商户订单编号
            param.put("nonce_str",WXPayUtil.generateNonceStr()); //随机字符

            //2、将参数转成xml字符，并携带签名
            String paramXml = WXPayUtil.generateSignedXml(param,partnerkey);

            //3、发送请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            httpClient.setHttps(true);
            httpClient.setXmlParam(paramXml);
            httpClient.post();

            //4、获取返回值，并将返回值转成Map
            String content = httpClient.getContent();
            return WXPayUtil.xmlToMap(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 关闭微信支付
     * @param orderId
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, String> closePay(Long orderId) throws Exception {
        //参数设置
        Map<String,String> paramMap = new HashMap<String,String>();
        paramMap.put("appid",appid); //应用ID
        paramMap.put("mch_id",partner);    //商户编号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());//随机字符
        paramMap.put("out_trade_no",String.valueOf(orderId));   //商家的唯一编号

        //将Map数据转成XML字符
        String xmlParam = WXPayUtil.generateSignedXml(paramMap,partnerkey);

        //确定url
        String url = "https://api.mch.weixin.qq.com/pay/closeorder";

        //发送请求
        HttpClient httpClient = new HttpClient(url);
        //https
        httpClient.setHttps(true);
        //提交参数
        httpClient.setXmlParam(xmlParam);

        //提交
        httpClient.post();

        //获取返回数据
        String content = httpClient.getContent();

        //将返回数据解析成Map
        return  WXPayUtil.xmlToMap(content);
    }
}
